# coding: utf-8

import os
import time
import json

from django.conf.urls import url
from django.http import JsonResponse

from project.settings import USER_TYPE
from apps.operators.handlers import (
    grade_subject_textbook_knowledge, customtag,
    topic, loginout, exam, question, lesson,
    qiniucloud, operator, news, push, booktext,
    school_class, mam, school, product,
    order, coupon, exam_book, goods, event)
from apps.operators.share import app_logger, danger_logger
from lib.common import LOG_ACTION_CHINESE

Error_Not_Login = JsonResponse({
    "retcode": 302,
    "msg": "未登录",
    "redirect": "/datainputer/login/login.html",
})
Error_Not_DATAINPUTER = JsonResponse({
    "retcode": 1,
    "msg": "请以数据操作员帐号登录",
    "redirect": "/datainputer/login/login.html",
})


def CheckUserIsFakeForApiCaller(request, *args, **kwargs):
    # if not request.user.is_authenticated():
    #     return Error_Not_Login

    execStartTime = time.time()

    if 'ut' not in request.session:
        return Error_Not_Login

    if request.session['ut'] not in (USER_TYPE.DATAINPUTER, USER_TYPE.TEMPINPUTER, USER_TYPE.OPERATOR, USER_TYPE.MAM, USER_TYPE.REGION, USER_TYPE.SHIPPER):
        return Error_Not_DATAINPUTER

    realCall = kwargs.pop('_viewFunc')

    ret = realCall(request, *args, **kwargs)

    if request.method in ('POST', 'DELETE', 'PUT'):
        url_path = request.path
        action_dict = LOG_ACTION_CHINESE.get(url_path.split('/')[3] if len(url_path.split('/')) > 4 else None)
        if not action_dict:
            danger_logger.info('!! 通知开发人员添加 [{method}] user_id : {user}, path : {path}, data: {data}'.format(method=request.method,user=request.session.get('_auth_user_id'),path=url_path,data=json.dumps(request.param_dict)))
        else:
            if request.method == 'DELETE':
                danger_logger.info('用户id {user} ，操作 {name} 模块，使用 删除 动作。路径 {path} ， 数据 {data} 。'.format(
                    user=request.session.get('_auth_user_id'),name= action_dict['name'],
                    path=url_path, data=json.dumps(request.param_dict)
                ))
            else:
                danger_logger.info('用户id {user} ，操作 {name} 模块，使用 {action} 动作。路径 {path} ， 数据 {data} 。'.format(
                    user=request.session.get('_auth_user_id'),name=action_dict['name'],
                    action = action_dict.get(request.param_dict.get('action'),'未知'),
                    path=url_path, data=json.dumps(request.param_dict)
                ))
    execEndTime = time.time()
    # 所有大于100ms的操作，产生日志告警
    opTime = execEndTime - execStartTime
    if (opTime > 0.1):
        app_logger.warning('!! op takes %s seconds : function:%s %s  ' % (opTime, request.method, request.path))

    return ret


urlpatterns_api = []


def addPreCheck(urlpatterns, checkFunC):
    for pattern in urlpatterns:
        urlRegx = pattern[0]
        if type(urlRegx) != list:
            urlRegList = [urlRegx]
        else:
            urlRegList = urlRegx

        viewFunc = pattern[1]
        if len(pattern) == 2:
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, {'_viewFunc': viewFunc}))

        elif len(pattern) == 3:
            otherPara = pattern[2]
            otherPara['_viewFunc'] = viewFunc
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, otherPara))
        else:
            # print '!!unsupported url format : %s' % pattern
            os._exit(3)


urlpatterns_api_agrs = [

    ([r'^yj_grades/$',
      r'^yj_grades/(?P<resource_id>\w+)/$'],
     grade_subject_textbook_knowledge.grade_handler.dispatch),

    ([r'^yj_subjects/$',
      r'^yj_subjects/(?P<resource_id>\w+)/$', ],
     grade_subject_textbook_knowledge.subject_handler.dispatch),

    ([r'^yj_subject_avatars/$',
      r'^yj_subject_avatars/(?P<resource_id>\w+)/$', ],
     grade_subject_textbook_knowledge.subject_avatar_handler.dispatch),

    ([r'^yj_textbookvers/$',
      r'^yj_textbookvers/(?P<resource_id>\w+)/$', ],
     grade_subject_textbook_knowledge.textbook_version_handler.dispatch),

    ([r'^yj_textbookvols/$',
      r'^yj_textbookvols/(?P<resource_id>\w+)/$', ],
     grade_subject_textbook_knowledge.textbook_volumn_handler.dispatch),

    ([r'^yj_textbookunits/$',
      r'^yj_textbookunits/(?P<resource_id>\w+)/$', ],
     grade_subject_textbook_knowledge.textbook_unit_handler.dispatch),

    ([r'^yj_knowledgestruct/$',
      r'^yj_knowledgestruct/(?P<resource_id>\w+)/$', ],
     grade_subject_textbook_knowledge.knowledge_struct_handler.dispatch),

    ([r'^yj_questiontags/$',
      r'^yj_questiontags/(?P<resource_id>\w+)/$', ],
     customtag.question_tag_handler.dispatch),

    ([r'^yj_examtags/$',
      r'^yj_examtags/(?P<resource_id>\w+)/$', ],
     customtag.exam_tag_handler.dispatch),

    ([r'^yj_lessontags/$',
      r'^yj_lessontags/(?P<resource_id>\w+)/$', ],
     customtag.lesson_tag_handler.dispatch),

    ([r'^yj_questions/$',
      r'^yj_questions/(?P<question_type>\w+)/$',
      r'^yj_questions/(?P<question_type>\w+)/(?P<resource_id>\w+)/$', ],
     question.question_handler.dispatch),

    ([r'^yj_exams/$',
      r'^yj_exams/(?P<resource_id>\w+)/$', ],
     exam.exam_handler.dispatch),

    ([r'^yj_exam_book/$',
      r'^yj_exam_book/(?P<resource_id>\w+)/$', ],
     exam_book.exam_book_handler.dispatch),

    ([r'^yj_lessons/$',
      r'^yj_lessons/(?P<resource_id>\w+)/$', ],
     lesson.lesson_handler.dispatch),

    (r'^yj_operator/$',
     operator.handler.dispatch),

    (r'^qiniu/$',
     qiniucloud.qiniu_handler.dispatch),

    (r'^news/$',
     news.handler.dispatch),

    (r'^push/$',
     push.handler.dispatch),

    (r'^yj_special_topic/$',
     topic.handler.dispatch),

    ([r'^yj_booktext/$',
      r'^yj_booktext/(?P<resource_id>\w+)/$', ],
     booktext.handler.dispatch),

    (r'^schoolclass/$',
     school_class.handler.dispatch),

    (r'^yj_schools/$',
     school.handler.dispatch),

    (r'^mam/$',
     mam.handler.dispatch),

    (r'^product/$',
     product.handler.dispatch),

    ([r'^orders/$',
      r'^orders/(?P<resource_id>\w+)/$'],
     order.handler.dispatch),

    (r'yj_coupon/$',
     coupon.handler.dispatch),

    (r'^yj_goods/$',
     goods.handler.dispatch),
    ([r'^yj_event/$',
      r'^yj_event/(?P<resource_id>\w+)/$'],
     event.handler.dispatch),
]

addPreCheck(urlpatterns_api_agrs, CheckUserIsFakeForApiCaller)

urlpatterns = [
    url(r'^loginReq$', loginout.handler.loginReq),
    url(r'^logoutreq$', loginout.handler.logoutReq),
    url(r'^parse_doc$', exam_book.exam_book_handler.handle_parse_doc),
] + urlpatterns_api
